package com.srb.sms.service.impl;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import com.srb.common.exception.Assert;
import com.srb.common.exception.BusinessException;
import com.srb.common.result.ResponseEnum;
import com.srb.sms.service.SmsService;
import com.srb.sms.util.SmsProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

    @Override
    public void send(String mobile, String templateCode, Map<String, Object> param) {
        //创建远程连接的客户端
        DefaultProfile profile = DefaultProfile.getProfile(SmsProperties.REGION_ID,
                SmsProperties.KEY_ID,SmsProperties.KEY_SECRET);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        //创建远程连接的请求参数
        CommonRequest request = new CommonRequest();
        request.setSysMethod(MethodType.POST);
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId",SmsProperties.REGION_ID);
        request.putQueryParameter("PhoneNumbers",mobile);
        request.putQueryParameter("SignName",SmsProperties.SIGN_NAME);
        request.putQueryParameter("TemplateCode",templateCode);
        Gson gson = new Gson();
        String jsonParam = gson.toJson(param);
        request.putQueryParameter("TemplateParam",jsonParam);
        CommonResponse response = null;
        try {
            //使用客户端对象携带请求向远程阿里云服务端发起远程调用,并得到响应结果
            response = client.getCommonResponse(request);
            //通信失败
            boolean success = response.getHttpResponse().isSuccess();
            Assert.isTrue(success,ResponseEnum.ALIYUN_RESPONSE_ERROR);
            String data = response.getData();
            HashMap<String,String> map = gson.fromJson(data, HashMap.class);
            String code = map.get("Code");
            String message = map.get("Message");
            log.info("code: {},message: {}",code,message);
            //业务失败
            Assert.notEquals("isv.BUSINESS_LIMIT_CONTROL",code,ResponseEnum.ALIYUN_SMS_LIMIT_CONTROL_ERROR);
            Assert.equals("OK",code,ResponseEnum.ALIYUN_SMS_ERROR);
        } catch (ClientException e) {
            log.error("客户端请求远程阿里云服务发送短信异常 {} , {}", e.getErrCode(),e.getErrMsg());
            throw new BusinessException(ResponseEnum.ALIYUN_SMS_ERROR,e);
        }
        log.info("=========data: {}",response.getData());
    }
}
